package com.TinyBBS.servlet;

import java.io.IOException;
import java.security.Security;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.TinyBBS.bean.User;
import com.TinyBBS.db.Config;
import com.TinyBBS.model.UserModel;
import com.TinyBBS.util.Util;

/**
 * Servlet implementation class RetrievePassword
 */
public class RetrievePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uri = "";
		String error = "";
		if (request.getParameter("retrievesubmit") == null) {
			uri = "views/retrievePassword.jsp";
		} else {
			String email = request.getParameter("email").trim();
			UserModel userM = new UserModel();
			User user = new User();
			user = userM.getUserByEmail(email);
			if (user != null) {
				try {
					HttpSession session = request.getSession();
					session.setAttribute("emailIdentity", user.getEmail());
					Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
					String[] sendTo = { "heli_070419@hotmail.com" };
					String emailMsgTxt = "<html><body><div>Hello,</div>";
					emailMsgTxt += "<div>	Your token is:"
							+ user.getToken()
							+ "</div>"
							+ "<div>Please enter this token to change your password.</div><br/><br/>";
					emailMsgTxt += "<div>regards</div><div>TinyBBS</div>";
					String emailSubjectTxt = "Token from TinyBBS";
					Util.sendSSLMessage(sendTo, emailSubjectTxt, emailMsgTxt,
							Config.EMAIL_FROM);
					uri = "views/sendEmail.jsp";
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				error = "Email does not exist, please check email again";
				uri = "views/retrievePassword.jsp";
			}

		}
		request.setAttribute("error", error);
		RequestDispatcher rd = request.getRequestDispatcher(uri);
		rd.forward(request, response);
	}
}
